//
//  RechargeViewController.m
//  DaoZiJinFu
//
//  Created by woker on 16/6/27.
//  Copyright © 2016年 iwoker. All rights reserved.
//

#import "RechargeViewController.h"
#import "AssetViewController.h"
#import "PaymentConfirm.h"

#define RechargeUnderLine 100

@interface RechargeViewController () <paymentDelegate> {
    BOOL IsCreateRechargeOrder;
    BOOL IsPrePay;
    BOOL IsComfirmPay;
    
    NSString *orderID;
    
    PaymentConfirm *pay;
    NSString *_orderId;
    
    NSTimer *timer;
    NSInteger timerFlag;
    DZBankInfo *_bankInfo;
}

@end

@implementation RechargeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupTitleView:@"充值"];
    self.view.backgroundColor = BACKGROUND_COLOR;
    [self leftButton:nil];

    _bankInfo = [DZBankInfo mj_objectWithKeyValues:[DZUserInfo.userInfo.banks firstObject]];
    [_bankIcon sd_setImageWithURL:[NSURL URLWithString:_bankInfo.bank_logo_path] placeholderImage:[UIImage imageNamed:LOGO_PLACEHOLDER]];
    _bankLab.text = _bankInfo.bank_name;
    NSString *cardNum = _bankInfo.bank_card_number;
    _cardTailNum.text = [NSString stringWithFormat:@"尾号%@",[cardNum substringFromIndex:cardNum.length-4]];
    _limitDescLab.text = _bankInfo.limit_desc;
    
    IsCreateRechargeOrder = NO;
    IsPrePay = NO;
    IsComfirmPay = NO;
    _nextBtn.layer.masksToBounds = YES;
    _nextBtn.layer.cornerRadius = BTN_RADIUS;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (IBAction)nextClick:(id)sender {
    if ([_rechargeMoney.text integerValue] < RechargeUnderLine) {
        NSString *string = [NSString stringWithFormat:@"充值金额不低于%d元",RechargeUnderLine];
        JSSHOW(string);
        return;
    }
    [self.view endEditing:YES];
    [JDHudUtil show];
    NSDictionary *params = @{@"bank_card_id":_bankInfo.id?:@"",
                             @"amount":_rechargeMoney.text};
    
    DZRequestUtil *request = [[DZRequestUtil alloc] init];
    request.requestUrl = @"Order/createRechargeOrder";
    request.params = params;
    [DZNetAPI request:request success:^(id response) {
        NSLog(@"%@",response);
        [JDHudUtil dismiss];
        DZResponse *model = [DZResponse mj_objectWithKeyValues:response];
        if (model.rt == 1) {
            _orderId = model.data[@"order_id"];
            orderID  = model.data[@"order_id"];
            [self createRechargeOrder:@""];
        } else{
            JSSHOW(model.msg);
        }
    } failure:^(NSError *error) {
        [JDHudUtil dismiss];
        JSSHOW(LOAD_FAIL_TIP);
    }];
}

- (void)createRechargeOrder:(NSString *)data {
    JSSHOWHUD;
    DZRequestUtil *request = [[DZRequestUtil alloc] init];
    request.requestUrl = @"Pay/prePay";
    request.params = @{@"id":_orderId?:@""};
    [DZNetAPI request:request success:^(id response) {
        NSLog(@"%@",response);
        JSHIDEHUD;
        DZResponse *model = [DZResponse mj_objectWithKeyValues:response];
        if (model.rt == 1) {
            pay = [PaymentConfirm showView:self.view withMobile:model.data[@"mobile"]];
            pay.delegate = self;
        }else{
            JSSHOW(model.msg);
        }
    } failure:^(NSError *error) {
        JSHIDEHUD;
        JSSHOW(LOAD_FAIL_TIP);
    }];
}

- (void)confirmRecharge:(NSString *)code {
    JSSHOWHUD;
    DZRequestUtil *request = [[DZRequestUtil alloc] init];
    request.requestUrl = @"Pay/confirmPay";
    request.params = @{@"sms_code":code?:@""};
    [DZNetAPI request:request success:^(id response) {
        NSLog(@"%@",response);
        JSHIDEHUD;
        DZResponse *model = [DZResponse mj_objectWithKeyValues:response];
        if (model.rt == 1) {
            [CommTools setUserInfo:response];
            [pay removeFromSuperview];
            pay = nil;
            JSSHOW(@"充值成功");
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.navigationController popToRootViewControllerAnimated:YES];
            });
        }else if(model.rt == 40007){
            JSSHOW(model.msg);
        }else{
            JSSHOW(model.msg);
        }
    } failure:^(NSError *error) {
        JSHIDEHUD;
        JSSHOW(LOAD_FAIL_TIP);
    }];
}

- (void)sendCode {
    JSSHOWHUD;
    DZRequestUtil *request = [[DZRequestUtil alloc] init];
    request.requestUrl = @"Pay/prePay";
    request.params = @{@"id":orderID?:@""};
    [DZNetAPI request:request success:^(id response) {
        JSHIDEHUD;
        DZResponse *model = [DZResponse mj_objectWithKeyValues:response];
        if (model.rt == 1) {
            JSSHOW(@"短信发送成功");
        }else{
            JSSHOW(model.msg);
        }
    } failure:^(NSError *error) {
        JSHIDEHUD;
        JSSHOW(LOAD_FAIL_TIP);
    }];
}

- (void)enterSuccessWait {
    [JDHudUtil showText:@"等待支付结果"];
    timerFlag = 0;
    timer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(getUserInfor) userInfo:nil repeats:YES];
}

- (void)getUserInfor {
    timerFlag ++;
    if (timerFlag == 4) {
        [JDHudUtil dismiss];
        [timer invalidate];
        JSSHOW(LOAD_FAIL_TIP);
        return;
    }
    DZgetOrderStatusRequest *request = [[DZgetOrderStatusRequest alloc] init];
    request.id = _orderId;
    request.order_type = @"2";
    [DZNetAPI request:request success:^(id response) {
        NSLog(@"%@",response);
        DZResponse *model = [DZResponse mj_objectWithKeyValues:response];
         if ([model.data isKindOfClass:[NSNumber class]] && [model.data integerValue] == 9) {
             [timer invalidate];
             [JDHudUtil dismiss];
             JSSHOW(@"充值成功");
             [[NSNotificationCenter defaultCenter] postNotificationName:@"updateAssetInformation" object:self];
             dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                 [self.navigationController popViewControllerAnimated:YES];
             });
         }
    } failure:^(NSError *error) {
    }];
}

- (IBAction)textChanged:(id)sender {
    if (_rechargeMoney.text.length) {
        _nextBtn.backgroundColor = BLUE_COLOR;
        _nextBtn.userInteractionEnabled = YES;
    } else {
        _nextBtn.backgroundColor = UNUSEABLECOLOR;
        _nextBtn.userInteractionEnabled = NO;
    }
}

- (void)leftBarItemOnClick:(id)sender {
    NSInteger index = NSIntegerMax;
    for (UIViewController *vc in self.navigationController.viewControllers) {
        if ([vc isMemberOfClass:[AssetViewController class]]) {
            index = [self.navigationController.viewControllers indexOfObject:vc];
            break;
        }
    }
    if (index != NSIntegerMax) {
        [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:index] animated:YES];
    } else {
        [self.navigationController popToRootViewControllerAnimated:YES];
    }
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if (string.length && ![CommTools isPureNumandCharacters:string]) {
        return NO;
    }
    return YES;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [SVProgressHUD dismiss];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeNone];
}

- (void)dealloc
{
    JSHIDEHUD;
}

@end
